<template>
  <div id="contestsView">
    <a-card :bordered="false">
      <a-space direction="vertical" :size="16" style="width: 100%">
        <a-row>
          <a-col :span="18">
            <a-form layout="inline">
              <a-form-item label="名称">
                <a-input
                  v-model:value="searchParams.title"
                  placeholder="请输入竞赛名称"
                />
              </a-form-item>
              <a-form-item label="类型">
                <a-select
                  v-model:value="searchParams.contestType"
                  style="min-width: 100px"
                  placeholder="竞赛类型"
                >
                  <a-select-option :value="null">全部</a-select-option>
                  <a-select-option :value="0">公开</a-select-option>
                  <a-select-option :value="1">密码保护</a-select-option>
                  <a-select-option :value="2">私有</a-select-option>
                </a-select>
              </a-form-item>
              <a-form-item label="状态">
                <a-select
                  v-model:value="searchParams.status"
                  style="min-width: 100px"
                  placeholder="竞赛状态"
                >
                  <a-select-option :value="null">全部</a-select-option>
                  <a-select-option :value="0">未开始</a-select-option>
                  <a-select-option :value="1">进行中</a-select-option>
                  <a-select-option :value="2">已结束</a-select-option>
                </a-select>
              </a-form-item>
              <a-form-item>
                <a-button type="primary" @click="doSearch">搜索</a-button>
              </a-form-item>
            </a-form>
          </a-col>
          <a-col :span="6" style="text-align: right">
            <a-button type="primary" @click="toAddContest">创建竞赛</a-button>
          </a-col>
        </a-row>
        <div style="background: #ff0; padding: 10px">
          <h3>当前数据检查：</h3>
          <p>是否加载中: {{ loading }}</p>
          <p>数据量: {{ contestList.length }}条</p>
          <p>首条数据: {{ JSON.stringify(contestList[0]) }}</p>
        </div>
        <a-tabs v-model:activeKey="activeTabKey" @change="handleTabChange">
          <a-tab-pane key="all" tab="全部竞赛">
            <a-table
              :columns="columns"
              :data-source="contestList"
              :loading="loading"
              :pagination="{
                current: current,
                pageSize: pageSize,
                total: total,
                showSizeChanger: true,
                showTotal: (total) => `共 ${total} 条`,
              }"
              @change="handleTableChange"
              :rowKey="(record) => record.id"
            >
              <template #bodyCell="{ column, record }">
                <template v-if="column.dataIndex === 'title'">
                  <a @click="toContestDetail(record)">{{ record.title }}</a>
                </template>
                <template v-if="column.dataIndex === 'contestType'">
                  <a-tag :color="getContestTypeColor(record.contestType)">
                    {{ getContestTypeText(record.contestType) }}
                  </a-tag>
                </template>
                <template v-if="column.dataIndex === 'status'">
                  <a-tag :color="getStatusColor(record.status)">
                    {{ getStatusText(record.status) }}
                  </a-tag>
                </template>
                <template v-if="column.dataIndex === 'startTime'">
                  {{ formatDate(record.startTime) }}
                </template>
                <template v-if="column.dataIndex === 'action'">
                  <a-space>
                    <a-button
                      type="primary"
                      size="small"
                      @click="toContestDetail(record)"
                    >
                      查看
                    </a-button>
                    <a-button
                      v-if="!record.hasRegistered"
                      type="default"
                      size="small"
                      @click="showRegisterModal(record)"
                    >
                      报名
                    </a-button>
                    <a-button
                      v-else-if="record.status === 1"
                      type="default"
                      size="small"
                      @click="startContest(record)"
                    >
                      开始
                    </a-button>
                  </a-space>
                </template>
              </template>
            </a-table>
          </a-tab-pane>
          <a-tab-pane key="registered" tab="我注册的竞赛">
            <a-list
              :loading="registeredLoading"
              item-layout="horizontal"
              :data-source="registeredContests"
            >
              <template #renderItem="{ item }">
                <a-list-item>
                  <a-list-item-meta :description="item.description">
                    <template #title>
                      <a @click="toContestDetail(item)">{{ item.title }}</a>
                    </template>
                  </a-list-item-meta>
                  <template #actions>
                    <a-tag :color="getStatusColor(item.status)">
                      {{ getStatusText(item.status) }}
                    </a-tag>
                    <a-button
                      v-if="item.status === 1"
                      type="primary"
                      size="small"
                      @click="startContest(item)"
                    >
                      开始竞赛
                    </a-button>
                    <a-button
                      v-else-if="item.status === 0"
                      type="default"
                      size="small"
                      disabled
                    >
                      未开始
                    </a-button>
                    <a-button v-else type="default" size="small" disabled>
                      已结束
                    </a-button>
                  </template>
                </a-list-item>
              </template>
            </a-list>
          </a-tab-pane>
          <a-tab-pane
            key="created"
            tab="我创建的竞赛"
            v-if="user?.userRole === 'admin'"
          >
            <a-list
              :loading="createdLoading"
              item-layout="horizontal"
              :data-source="createdContests"
            >
              <template #renderItem="{ item }">
                <a-list-item>
                  <a-list-item-meta :description="item.description">
                    <template #title>
                      <a @click="toContestDetail(item)">{{ item.title }}</a>
                    </template>
                  </a-list-item-meta>
                  <template #actions>
                    <a-tag :color="getStatusColor(item.status)">
                      {{ getStatusText(item.status) }}
                    </a-tag>
                    <a-button
                      type="primary"
                      size="small"
                      @click="toEditContest(item)"
                    >
                      编辑
                    </a-button>
                  </template>
                </a-list-item>
              </template>
            </a-list>
          </a-tab-pane>
        </a-tabs>
      </a-space>
    </a-card>

    <!-- 竞赛注册弹窗 -->
    <a-modal
      v-model:visible="registerModalVisible"
      title="竞赛报名"
      @ok="doRegister"
      okText="报名"
      cancelText="取消"
    >
      <a-form
        :model="registerForm"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 18 }"
      >
        <a-form-item label="竞赛标题" name="title">
          <span>{{ currentContest?.title }}</span>
        </a-form-item>
        <a-form-item label="竞赛时间" name="time">
          <span>{{ formatDate(currentContest?.startTime) }}</span>
        </a-form-item>
        <a-form-item label="竞赛时长" name="duration">
          <span>{{ currentContest?.duration }} 分钟</span>
        </a-form-item>
        <a-form-item
          v-if="currentContest?.contestType === 1"
          label="竞赛密码"
          name="password"
        >
          <a-input-password
            v-model:value="registerForm.password"
            placeholder="请输入竞赛密码"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
/* eslint-disable */
import { onMounted, ref, reactive } from "vue";
import { useRouter } from "vue-router";
import { message } from "ant-design-vue";
import { ContestControllerService } from "../../../generated/services/ContestControllerService";
import { useStore } from "vuex";
import { formatDate } from "@/utils/dateUtil";

// 初始化数据
const router = useRouter();
const store = useStore();
const user = store.state.user.loginUser;

// 竞赛列表数据
const loading = ref(false);
const contestList = ref([]);
const current = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 明确定义表格列，与 ContestVO 数据结构对应
const columns = [
  {
    title: "竞赛名称",
    dataIndex: "title",
    key: "title",
    width: "25%",
  },
  {
    title: "开始时间",
    dataIndex: "startTime",
    key: "startTime",
    width: "15%",
  },
  {
    title: "时长",
    dataIndex: "duration",
    key: "duration",
    width: "10%",
    customRender: ({ text }) => `${text} 分钟`,
  },
  {
    title: "类型",
    dataIndex: "contestType",
    key: "contestType",
    width: "10%",
  },
  {
    title: "状态",
    dataIndex: "status",
    key: "status",
    width: "10%",
  },
  {
    title: "参与人数",
    dataIndex: "registrationCount",
    key: "registrationCount",
    width: "10%",
  },
  {
    title: "操作",
    dataIndex: "action",
    key: "action",
    width: "20%",
  },
];

// 搜索参数
const searchParams = reactive({
  title: "",
  contestType: null,
  status: null,
  current: 1,
  pageSize: 10,
});

// 标签页
const activeTabKey = ref("all");
const registeredContests = ref([]);
const createdContests = ref([]);
const registeredLoading = ref(false);
const createdLoading = ref(false);

// 报名相关
const registerModalVisible = ref(false);
const currentContest = ref();
const registerForm = reactive({
  contestId: undefined,
  password: "",
});

// 加载竞赛列表
const loadData = async () => {
  try {
    loading.value = true;
    // 构建请求参数
    const params = {
      title: searchParams.title || undefined,
      contestType:
        searchParams.contestType !== null
          ? searchParams.contestType
          : undefined,
      status: searchParams.status !== null ? searchParams.status : undefined,
      current: searchParams.current,
      pageSize: searchParams.pageSize,
      sortField: "createTime",
      sortOrder: "descend",
    };
    console.log("请求参数:", params);
    const res = await ContestControllerService.listContestByPageUsingPost(
      params
    );
    console.log("获取到的竞赛数据:", res);
    if (res.code === 0 && res.data) {
      // 确保 contestList 是响应式数组
      if (Array.isArray(res.data.records)) {
        contestList.value = [...res.data.records];
      } else {
        contestList.value = [];
      }
      console.log("获取到的比赛列表数据:", contestList.value);
      // 打印第一条数据的详细信息，帮助调试
      if (contestList.value.length > 0) {
        console.log("第一条数据:", JSON.stringify(contestList.value[0]));
      }

      total.value = res.data.total || 0;
      current.value = res.data.current || 1;
      pageSize.value = res.data.size || 10;
    } else {
      message.error("获取竞赛列表失败: " + (res.message || "未知错误"));
      contestList.value = [];
    }
  } catch (error) {
    console.error("获取竞赛列表异常", error);
    message.error("获取竞赛列表异常");
    contestList.value = [];
  } finally {
    loading.value = false;
  }
};

// 加载我注册的竞赛
const loadRegisteredContests = async () => {
  try {
    registeredLoading.value = true;
    const res =
      await ContestControllerService.getMyRegisteredContestsUsingGet();
    if (res.code === 0) {
      registeredContests.value = res.data || [];
    } else {
      message.error("获取我注册的竞赛失败");
      registeredContests.value = [];
    }
  } catch (error) {
    console.error("获取我注册的竞赛异常", error);
    registeredContests.value = [];
  } finally {
    registeredLoading.value = false;
  }
};

// 加载我创建的竞赛
const loadCreatedContests = async () => {
  try {
    createdLoading.value = true;
    const res = await ContestControllerService.getMyCreatedContestsUsingGet();
    if (res.code === 0) {
      createdContests.value = res.data || [];
    } else {
      message.error("获取我创建的竞赛失败");
      createdContests.value = [];
    }
  } catch (error) {
    console.error("获取我创建的竞赛异常", error);
    createdContests.value = [];
  } finally {
    createdLoading.value = false;
  }
};

// 搜索
const doSearch = () => {
  searchParams.current = 1;
  loadData();
};

// 表格翻页
const handleTableChange = (pagination) => {
  searchParams.current = pagination.current;
  searchParams.pageSize = pagination.pageSize;
  loadData();
};

// 竞赛类型显示
const getContestTypeText = (type) => {
  const typeMap = {
    0: "公开",
    1: "密码保护",
    2: "私有",
  };
  return typeMap[type] || "未知";
};

const getContestTypeColor = (type) => {
  const colorMap = {
    0: "green",
    1: "blue",
    2: "purple",
  };
  return colorMap[type] || "default";
};

// 竞赛状态显示
const getStatusText = (status) => {
  const statusMap = {
    0: "未开始",
    1: "进行中",
    2: "已结束",
  };
  return statusMap[status] || "未知";
};

const getStatusColor = (status) => {
  const colorMap = {
    0: "blue",
    1: "green",
    2: "red",
  };
  return colorMap[status] || "default";
};

// 跳转到竞赛详情
const toContestDetail = (record) => {
  router.push(`/contest/${record.id}`);
};

// 跳转到创建竞赛
const toAddContest = () => {
  router.push("/contest/add");
};

// 跳转到编辑竞赛
const toEditContest = (record) => {
  router.push(`/contest/edit/${record.id}`);
};

// 显示报名弹窗
const showRegisterModal = (record) => {
  currentContest.value = record;
  registerForm.contestId = record.id;
  registerForm.password = "";
  registerModalVisible.value = true;
};

// 报名竞赛
const doRegister = async () => {
  try {
    const res = await ContestControllerService.registerContestUsingPost({
      contestId: registerForm.contestId,
      password: registerForm.password,
    });
    if (res.code === 0) {
      message.success("报名成功");
      registerModalVisible.value = false;
      loadData();
      loadRegisteredContests();
    } else {
      message.error(res.message || "报名失败");
    }
  } catch (error) {
    console.error("报名竞赛异常", error);
    message.error("报名失败");
  }
};

// 开始竞赛
const startContest = async (record) => {
  try {
    const res = await ContestControllerService.startContestUsingPost(record.id);
    if (res.code === 0) {
      message.success("开始竞赛成功");
      router.push(`/contest/${record.id}`);
    } else {
      message.error(res.message || "开始竞赛失败");
    }
  } catch (error) {
    console.error("开始竞赛异常", error);
    message.error("开始竞赛失败");
  }
};

// 监听标签页切换
const handleTabChange = () => {
  if (activeTabKey.value === "registered") {
    loadRegisteredContests();
  } else if (activeTabKey.value === "created") {
    loadCreatedContests();
  }
};

// 页面加载
onMounted(() => {
  console.log("页面挂载，开始加载数据");
  // 初始化搜索参数
  searchParams.title = "";
  searchParams.contestType = null;
  searchParams.status = null;
  searchParams.current = 1;
  searchParams.pageSize = 10;

  // 加载数据
  loadData();

  // 如果用户已登录，加载相关数据
  if (user) {
    loadRegisteredContests();
    if (user.userRole === "admin") {
      loadCreatedContests();
    }
  }
});
</script>

<style scoped>
#contestsView {
  padding: 24px;
}
</style>
